<template>
  <div class="login">
    <div class="box">
      <el-card shadow="hover" style="height: 100%">
        <div slot="header" class="clearfix">
          <span>管理员登录</span>
        </div>
        <el-form
          ref="userForm"
          :model="user"
          label-position="left"
          label-width="70px"
          :rules="rules"
        >
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="user.username"
              placeholder="请输入用户名"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="user.password"
              placeholder="请输入密码"
              show-password
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit('userForm')"
              >登录</el-button
            >
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import { reqLogin } from "../api";
import { saveUser } from "../utils";

export default {
  name: "Login",
  // data
  data() {
    return {
      user: {
        username: "",
        password: "",
      },

      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    };
  },
  // methods
  methods: {
    onSubmit(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const { success, data } = await reqLogin(this.user);
          if (success) {
            const { admin } = data;
            saveUser(admin);
            this.$message({
              message: `登陆成功，欢迎你: ${admin.username}`,
              type: "success",
            });
            this.$router.history.replace("/admin");
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style>
#app {
  width: 100%;
  height: 100%;
}
.login {
  width: 100%;
  height: 100%;
  background: url("../assert/images/1.webp") no-repeat center;
  position: relative;
}
.box {
  width: 400px;
  height: 300px;
  background-color: skyblue;
  position: absolute;
  top: 15%;
  left: 50%;
}
</style>